#coding=utf-8
import time
import json
import requests
import yagmail

# 信息声明

config = json.load(open('./config.json', 'r'))

email = config['email']
# 邮箱地址
authCode = config['authCode']
# 需配置QQ邮箱的授权码
host = config['host']

uName = config['uName']
# u+用户名
uPassword = config['uPassword']
# u+密码


def getDateStr():
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))


def login(usernam, password):
    token = ''

    if usernam!='' and password!='':
        headers = {
            'Content-Type': 'application/json',
        }
        payload = {
            'appId': 'A270_',
            'userName': usernam,
            'password': password,
        }
        try:
            login = requests.post('https://gateway.eec-cn.com/base/api/login', headers=headers, data=json.dumps(payload))
        except requests.exceptions.ConnectionError:
            print('无网络连接！%s' % getDateStr())
        else:
            if login.headers['Content-Type'] == 'application/json;charset=UTF-8':
                if login.status_code == 200:
                    resp = login.json()
                    if resp['code'] == 200:
                        data = resp['data']
                        token = data['token']
                        print('登录成功！%s' % getDateStr())
                    else:
                        print(resp['message'])
                else:
                    print('用户名密码出错！%s' % getDateStr())
            else:
                print('登录出错！%s' % getDateStr())
    else:
        print('用户名或密码为空，请检查conf.json！')
    
    return token


def fetchMsg(token):
    headers = { 'Authorization': token }
    msgContent = ''
    try:
        req = requests.get('https://gateway.eec-cn.com/base/api/messages/noRead', headers=headers)
    except requests.exceptions.ConnectionError:
        print('无网络连接！%s' % getDateStr())
    else:
        if req.headers['Content-Type'] == 'application/json;charset=UTF-8':
            if req.status_code == 200:
                data = req.json()['data']
                
                newMessages = filter(lambda msg: msg['isRead']==0, data)
                for message in newMessages:
                    msgContent += '<h4>时间：%s</h4>' % message['receiveTime']
                    msgContent += '<h4>标题：%s</h4>' % message['title']
                    msgContent += '<h4>内容：%s</h4>' % message['content']

                if (msgContent != ''):
                    # 只在有新消息时，添加往期消息
                    oldMessages = filter(lambda msg: msg['isRead']==1, data)
                    msgContent += '\n往期通知：\n'
                    for message in oldMessages:
                        msgContent += '\n时间：%s\n' % message['receiveTime']
                        msgContent += '标题：%s\n' % message['title']
                        msgContent += '内容：%s\n' % message['content']
                    
                    print('获取信息成功！%s' % getDateStr())
                else:
                    print('没有新通知 %s' % getDateStr())
            else:
                print('验证失败！%s' % getDateStr())
                print(req.status_code)
        else:
            print('请求出错！%s' % getDateStr())
    
    return msgContent


def sendEmail(title, content):
    yag = yagmail.SMTP( user=email, password=authCode, host=host)
    print('发送邮件...')
    yag.send('1830570001@qq.com', title, [content])


def main():
    print('U+通知系统启动...')
    while True:
        emailContent = fetchMsg(login(uName, uPassword))
        if emailContent != '':
            sendEmail('😱【%s】U+有新通知啦！📌' % getDateStr(), emailContent)
        
        time.sleep(600)
        # 十分钟询问一次


if __name__ == '__main__':
    main()
